﻿using System.Collections.Generic;

public delegate void SetBytes(string key, byte[] ab);

public class ByteLoadMgr : Singleton<ByteLoadMgr>
{
    private Dictionary<string, List<SetBytes>> cacheDic;
    private Dictionary<string, byte[]> resourceDic;
    private ZLoaderQueen queen;

    public ByteLoadMgr()
    {
        queen = new ZLoaderQueen("资源包加载");
        cacheDic = new Dictionary<string, List<SetBytes>>();
        resourceDic = new Dictionary<string, byte[]>();

        queen.QueenModel.AddEvent(ConstData.COMPLETE, OnComplete);
        queen.QueenModel.AddEvent(ConstData.CHILD_COMPLETE, OnChildComplete);
        queen.QueenModel.AddEvent(ConstData.CHANGE, OnChange);
        queen.AddEvent(ConstData.ERROR, OnError);
    }

    /// <summary>
    /// 加载ab 资源包
    /// </summary>
    /// <param name="url">路径</param>
    /// <param name="key">加载完成回调标识</param>
    /// <param name="setAB">加载完成回调函数</param>
    public void GetAssetBundle(string url, SetBytes setAB, string key = null)
    {
        if (resourceDic.ContainsKey(url))
        {
            setAB.Invoke(key, resourceDic[url]);
            return;
        }
        if (!cacheDic.ContainsKey(url))
        {
            cacheDic.Add(url, new List<SetBytes>());
        }
        if (!cacheDic[url].Contains(setAB))
        {
            cacheDic[url].Add(setAB);
        }
        queen.Add(new WWWLoader(url, key));
        queen.Load();
        UpdateMgr.GetSingleton().AddUpdate(queen);
    }

    public void Clear()
    {
        queen.Clear();
        cacheDic.Clear();
        resourceDic.Clear();
    }

    private void OnError(object sender, EventArg eventArg)
    {
        WWWLoader loader = sender as WWWLoader;
        EDebug.Log("加载失败：" + loader.Www.error);
    }

    private void OnChange(object sender, EventArg eventArg)
    {

    }

    private void OnChildComplete(object sender, EventArg eventArg)
    {
        WWWLoader loader = queen.CurLoader as WWWLoader;
        string url = loader.Request.url;
        string key = loader.Request.key;
        resourceDic.Add(url, loader.Www.bytes);
        List<SetBytes> cacheList = cacheDic[url];
        while (cacheList.Count > 0)
        {
            cacheList[0].Invoke(key, resourceDic[url]);
            cacheList.RemoveAt(0);
        }
        cacheDic[url] = null;
        cacheDic.Remove(url);
    }

    private void OnComplete(object sender, EventArg eventArg)
    {
        UpdateMgr.GetSingleton().RemoveUpdate(queen);
        ZEventCenter.DispatchEvent(new ZEvent(ConstData.ABMGR_LOAD_COMPLETE));
    }
}